const args = getArgs();
import Request from "./request.js";

const request = new Request(args.key, args.secret)

for (let i = 0; i < args.prefix.length; i++) {
    const prefix = args.prefix[i]
    request.getAliDnsIp({
        RR: prefix,
        domain: args.domain
    }).then(record => {
        if (!record) {
            console.warn(`未查询到 [${prefix}.${args.domain}] 的记录！跳过执行`)
            return
        }
        const remoteIp = record.Value
        console.log(`aliddns：查询到ip： ${prefix}.${args.domain} --> ${remoteIp}`)
        const type = getType(record.Type)
        request.getLocalIp(type).then(localIp => {
            if (remoteIp === localIp) {
                console.log('aliddns：ip相同不执行替换策略')
                return
                // process.exit()
            }
            request.executeUpdate({record, newValue: localIp}).then(() => {
                console.log(`aliddns: 更换ip成功 当前ip：${prefix}.${args.domain}-->${localIp}`);
            })
        }).catch(e => {
            if (e.hostname && e.hostname.toLowerCase().indexOf('ipv6-test') > -1) {
                console.warn(`当前系统未启用ip${type} 跳过执行：${prefix}.${args.domain}`)
            }
            throw e
        })
    }).catch(e => {
        throw e
    })
}


function getArgs() {
    if (!process.env.key) {
        throw new Error('key不能为空')
    }
    if (!process.env.secret) {
        throw new Error('secret不能为空')
    }
    if (!process.env.domain) {
        throw new Error('域名不能为空')
    }
    let prefix = process.env.prefix
    if (!prefix) {
        throw new Error('域名前缀不能为空')
    }
    prefix = prefix.split(',')
    return {
        key: process.env.key,
        secret: process.env.secret,
        domain: process.env.domain,
        prefix
    }
}

function getType(type) {
    if (type === 'A') {
        return 'v4'
    } else if (type === 'AAAA') {
        return 'v6'
    } else {
        throw new Error(`不支持的type ：${type}`)
    }
}